package org.example.Tool.Component;

import org.example.Tool.IRunFunc;
import org.example.Tool.ISelectable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.JarURLConnection;
import java.net.URL;


public class CheckCard extends JLabel implements ISelectable {
    protected JLabel label;

    private IRunFunc clickEvent;

    private IRunFunc Event;

    private boolean selected = false;

    protected final AdjustIconBuilder currentIconBuilder;
    {
        AdjustIconBuilder tempIcon = new AdjustIconBuilder();

        try {
            URL url = CheckCard.class.getResource("/Image/CheckCard_default.png");
            if (url != null) {
                tempIcon.setImage(Toolkit.getDefaultToolkit().getImage(url));
            } else
                throw new RuntimeException("static: failed to load default icon");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        currentIconBuilder = tempIcon;
    }

    public CheckCard(String title, Rectangle rectangle) {
        this(title);
        this.setBounds(rectangle);
    }

    public CheckCard(String title, Image image) {
        super();
        currentIconBuilder.setComponent(this);
        if (image != null)
            currentIconBuilder.setImage(image);
        this.setIcon(currentIconBuilder.of());
        label = new JLabel(title);
        this.add(label);
        label.setVisible(true);

        this.setName(title);
        this.init();

    }

    public CheckCard(String title) {
        this(title, (Image) null);
    }

    public CheckCard() {
        this("");
    }

    protected void init() {
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (clickEvent != null)
                    clickEvent.run();
            }
        });
        this.addComponentListener(new ComponentAdapter(){
            @Override
            public void componentResized(ComponentEvent e) {
                super.componentResized(e);
                final int width = label.getText().length() * 16;
                Component _parent = e.getComponent();
                label.setBounds(
                        (_parent.getSize().width - width) / 2,
                        _parent.getSize().height / 2 - 10,
                        width,
                        16);
            }
        });
    }

    @Override
    public void setName(String name) {
        super.setName(name);
        label.setText(name);
    }

    public void setClickEvent(IRunFunc clickEvent) {
        this.clickEvent = clickEvent;
    }

    @Override
    public boolean isSelected() {
        return selected;
    }

    @Override
    public void toBeSelected(boolean bool) {
        selected = bool;
    }
}
